<?php

namespace Henan\ThinkSdk\service;


use Exception;
use OSS\Core\OssException;
use OSS\OssClient;
use think\facade\Config;
use think\file\UploadedFile;

/**
 * 阿里云储存服务类
 * @author henan
 */
class OssService
{
    /**
     * 构造函数
     * @param array $config
     */
    public function __construct(public array $config = [])
    {
        if (empty($this->config)) $this->config = Config::get('sdk.OssService');
    }

    /**
     * 上传本地文件
     * @param UploadedFile|string $file
     * @param string $dir 上传目录
     * @param string $ext 文件拓展名(为空字符串时，自动获取)
     * @return string 上传文件链接
     * @throws Exception
     */
    public function uploadFile(UploadedFile|string $file, string $dir, string $ext = ''): string
    {
        if (is_object($file)) {
            $filepath = $file->getPathname();
            $ext = empty($ext) ? $file->getOriginalExtension() : $ext;
        } else {
            $filepath = $file;
            $ext = empty($ext) ? pathinfo($filepath, PATHINFO_EXTENSION) : $ext;
        }
        $filename = $dir . '/' . date('Ymd') . '/' . date('His') . uniqid() . '.' . $ext;
        try {
            $config = $this->config;
            $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
            $ossClient->uploadFile($config['bucket'], $filename, $filepath);
        } catch (OssException|Exception $e) {
            throw new Exception($e->getMessage());
        }
        return 'https://' . $config['bucket'] . '.' . $config['endpoint'] . '/' . $filename;
    }

    /**
     * 对象上传内容
     * @param string $content 文件内容
     * @param string $ext 文件拓展名
     * @param string $dir 上传目录
     * @return string 上传文件链接
     * @throws Exception
     */
    public function uploadObject(string $content, string $ext, string $dir): string
    {
        $filename = $dir . '/' . date('Ymd') . '/' . date('His') . uniqid() . '.' . $ext;
        try {
            $config = $this->config;
            $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
            $ossClient->putObject($config['bucket'], $filename, $content);
        } catch (OssException|Exception $e) {
            throw new Exception($e->getMessage());
        }
        return 'https://' . $config['bucket'] . '.' . $config['endpoint'] . '/' . $filename;
    }
}